package org.lynn.ws.websocket;

import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt(json web token 工具类)
 * @author gy
 * @date 2019/3/3 14:35
 */
public class Jwt {

    private static final   Key key = new SecretKeySpec("javastack".getBytes(), SignatureAlgorithm.HS512.getJcaName());

    public static void main(String[] args) {
        String jwtEncode = jwtEncode();
        jwtDecode(jwtEncode);
    }


    private static String jwtEncode(){

        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("type", "1");
        String payload = "{\"user_id\":\"1341137\", \"expire_time\":\"2018-01-01 0:00:00\"}";
        String compactJwt = Jwts.builder().setHeader(stringObjectMap).setPayload(payload).signWith(SignatureAlgorithm.HS512, key).compact();

        System.out.println("jwt key:" + new String(key.getEncoded()));
        System.out.println("jwt payload:" + payload);
        System.out.println("jwt encoded:" + compactJwt);

        return compactJwt;

    }

    private static void jwtDecode(String compactJwt){

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(key).parseClaimsJws(compactJwt);
        JwsHeader header = claimsJws.getHeader();
        Claims body = claimsJws.getBody();

        System.out.println("jwt header:" + header);
        System.out.println("jwt body:" + body);
        System.out.println("jwt body user-id:" + body.get("user_id", String.class));


    }




}
